package crawler.demo;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

public class SimpleTest implements PageProcessor {

    private Site site = Site
            .me()
            .setSleepTime(3000)
            .setRetryTimes(3)
            .setCharset("utf-8")
            .setUserAgent(
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

    @Override
    public void process(Page page) {
        //page.putField("author", page.getUrl().regex("https://www.oschina.net/(\\w+)/.*").toString());
        //page.putField("header", page.getHtml().xpath("//div[@class='panel-content__column']/div[@class='panel-content']/a[@class='tool-item__inner']/text()"));
        if("https://www.oschina.net".equals(page.getUrl().get())){
            page.putField("header", page.getHtml().xpath("//div[@class='panel-box panel-box--question-career']//a[@class='item-title']/text()").all());
            List<String> links = page.getHtml().xpath("//div[@class='panel-box panel-box--question-career']//a[@class='item-title']/@href").all();
            page.putField("href", links);
            page.addTargetRequests(links);
        }
        if(page.getUrl().regex("https://www.oschina.net/question/\\w+").match()){
            page.putField("title",page.getHtml().xpath("//h1[@class='header article-title']/a/text()"));
            page.putField("content",page.getHtml().xpath("//div[@id='articleContent']").all());
        }
        //page.addTargetRequests(page.getHtml().links().regex("(https://www.oschina.net/question/\\w+)").all());
    }

    @Override
    public Site getSite() {
        return site;
    }

}
